package com.piece.file.preview;

import com.piece.core.framework.util.net.HttpUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.framework.util.file.CompressUtil;
import com.piece.core.framework.util.file.FileUtil;
import com.piece.file.support.FileAttribute;
import com.piece.file.client.FileClientFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Service
public class CompressFilePreview implements FilePreviewHandle {

    @Resource
    protected FileClientFactory fileClientFactory;

    @Override
    public String handle(FileAttribute fileAttribute, HttpServletRequest request, Model model, boolean edit) {
        String fileName = fileAttribute.getName();
        String suffix = FileUtil.getFileSuffix(fileName);
        String path = FileUtil.getTempPath() + File.separator + "compress";
        String fullPath = FileUtil.getTempPath() + File.separator + "compress" + File.separator + fileName;
        try {
            File localFile = new File(fullPath);
            if (localFile.exists()) {
                localFile.delete();
            }
            InputStream inputStream = HttpUtil.get(fileAttribute.getUrl()).execute().download();
            byte[] bytes = FileUtil.toByte(inputStream);
            fileClientFactory.getNative().writeToLocalStore(bytes, path, fileName);

            String fileTree = null;
            localFile = new File(fullPath);
            if ("zip".equalsIgnoreCase(suffix) || "jar".equalsIgnoreCase(suffix) || "gzip".equalsIgnoreCase(suffix)) {
                fileTree = CompressUtil.unZipFile(fullPath, path, false);
            } else if ("rar".equalsIgnoreCase(suffix)) {
                fileTree = CompressUtil.unRarFile(fullPath, path, false);
            }

            if (StringUtil.isNotEmpty(fileTree)) {
                model.addAttribute("file_tree", fileTree);
                return "/file/compress";
            }

            model.addAttribute("msg", "压缩文件类型不受支持");
            return "/file/fileNotSupported";
        } catch (IOException e) {
            model.addAttribute("msg", e.getMessage());
            return "/file/fileNotSupported";
        }
    }
}
